import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import lc.Services;
import lc.animation.Animation;
import lc.animation.AnimationController;
import lc.animation.AnimationDataController;
import lc.basic.BasicServices;
import lc.gui.support.LiteDesktopState;
import lc.util.CoincidentTextureLocator;

import com.jme.app.SimpleGame;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.input.action.InputActionEvent;
import com.jme.input.action.InputActionInterface;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.util.export.binary.BinaryImporter;
import com.jme.util.resource.ResourceLocatorTool;
import com.jmex.game.state.GameStateManager;


public class MeshViewer extends SimpleGame implements Runnable {

	MeshViewer() {
		services = new BasicServices();
		GameStateManager.create();
	}

	static final class OpenDialogAction implements InputActionInterface {
		OpenDialogAction(MeshViewer m) {
			mv = m;
		}
		public void performAction(InputActionEvent evt) {
			mv.showChooser();
		}
		MeshViewer mv;
	}
	Services services;
	LiteDesktopState lds;
	File fileToOpen;
	Spatial theModel;

	static OpenDialogAction openDialog;
	@Override
	protected void simpleInitGame() {
		openDialog = new OpenDialogAction(this);
		KeyBindingManager keyboard = KeyBindingManager.getKeyBindingManager();
		keyboard.set("open", KeyInput.KEY_O);
		input.addAction(openDialog, "open", false);
		services.setService("display", display);
		lds = new LiteDesktopState(services);
		fpsNode.attachChild(lds.getRootNode());
		File f = new File("data/model");
		fc = new JFileChooser(f);
		fc.setFileFilter(new ExtensionFileFilter(".jme", "jMonkeyEngine File"));
		showChooser();
	}

	public static class ExtensionFileFilter extends FileFilter {
		public ExtensionFileFilter(String e, String d) {
			end = e.toLowerCase();
			desc = d;
		}
		String end;
		String desc;
		@Override
		public boolean accept(File f) {
			return f.isDirectory() || f.getName().toLowerCase().endsWith(end);
		}
		@Override
		public String getDescription() {
			return desc;
		}
	}
	void showChooser() {
		if (fcShowing)
			return;
		fcShowing = true;
		new Thread(this).start();
	}

	protected void simpleUpdate() {
		File model = null;
		if (fileToOpen != null) {
			synchronized(this) {
				if (fileToOpen != null) {
					model = fileToOpen;
					fileToOpen = null;
				}
			}
		}
		if (model != null) {
			//	open the model
			openModel(model);
		}
	}

	void openModel(File f) {
		if (theModel != null) {
			theModel.removeFromParent();
			theModel = null;
		}
		String path = f.getAbsolutePath();
		int ix = path.lastIndexOf('/');
		if (ix < 0) {
			ix = path.lastIndexOf('\\');
		}
		if (ix > 0) {
			path = path.substring(0, ix);
			texturePath.basePath = path;
		}
		else {
			texturePath.basePath = null;
		}

		try {
			java.io.InputStream str = new java.io.FileInputStream(f);
			BinaryImporter bi = new BinaryImporter();
			Node cld = (Node)bi.load(str);
			str.close();
			cld.setLocalTranslation(0, 0, 0);
			rootNode.attachChild(cld);
			rootNode.updateRenderState();
			theModel = cld;
			Animation a = AnimationDataController.findAnimation(cld);
			if (a != null) {
				theModel.addController(new AnimationController(cld, a));
			}
			cam.setLocation(new Vector3f(0, 5, 25));
			cam.lookAt(new Vector3f(0, 2, 0), Vector3f.UNIT_Y);
			lds.setActive(false);
		} catch (java.lang.Exception x) {
			System.out.println("Exception loading model: " + x.getMessage() + "\n");
			x.printStackTrace();
		}
	}

	public static final CoincidentTextureLocator texturePath =
			new CoincidentTextureLocator();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, texturePath);
		MeshViewer mv = new MeshViewer();
		mv.start();
	}

	JFileChooser fc;
	boolean fcShowing;

	public void run() {
		int res = fc.showOpenDialog(lds.getDesktop().getJDesktop());
		if (res == JFileChooser.APPROVE_OPTION) {
			synchronized(this) {
				fileToOpen = fc.getSelectedFile();
			}
		}
		fcShowing = false;
	}

}
